package cn.darkhorse.meswechat.service.impl;

import cn.darkhorse.meswechat.common.WxChatAddress;
import cn.darkhorse.meswechat.common.WxChatCommon;
import cn.darkhorse.meswechat.dto.WxSendMessageDTO;
import cn.darkhorse.meswechat.service.IWeChatService;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import javassist.ClassPath;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: mr.wang
 * @time: 2023/4/14 14:44
 */
@Service
public class WeChatServiceImpl implements IWeChatService {
	
	@Resource
	RedisCache redisCache;
	
	
	@Override
	public void getServerToken() {
		String url = WxChatAddress.getToken();
		String responseder = HttpUtils.sendGet(url);
		System.out.println("获取公众号响应："+responseder);
		if(StringUtils.isNotBlank(responseder)){
			JSONObject jsonObject = JSONObject.parseObject(responseder);
			String token = jsonObject.getString("access_token");
			int expiresIn = jsonObject.getIntValue("expires_in");
			redisCache.setCacheObject(WxChatCommon.WX_TOKEN_CACHE_TIME,token,expiresIn, TimeUnit.SECONDS);
			System.out.println("公众号token:"+token+"===过期时长：（"+expiresIn+")秒");
		}
	}
	
	
	@Override
	public String getToken() {
		String token = redisCache.getCacheObject(WxChatCommon.WX_TOKEN_CACHE_TIME);
		if(StringUtils.isBlank(token)){
			//重新获取token
			getServerToken();
			token = redisCache.getCacheObject(WxChatCommon.WX_TOKEN_CACHE_TIME);
		}
		return token;
	}
	
	@Override
	public String getPicture() {
		Long userId = SecurityUtils.getUserId();
		String key = WxChatCommon.QR_CODE_KEY+":"+userId;
		String pUrl = redisCache.getCacheObject(key);
		if(StringUtils.isBlank(pUrl)){
		String url = WxChatAddress.getTicket(getToken());
		Map<String,Object> params = new HashMap<>();
		params.put("action_name","QR_SCENE");
		Map<String,Object> actionInfo = new HashMap<>();
		Map<String,Object> scene = new HashMap<>();
		scene.put("scene_id", userId);
		actionInfo.put("scene",scene);
		params.put("action_info",actionInfo);
		params.put("expire_seconds",WxChatCommon.QR_CODE);
		String responseder = HttpUtils.sendPost(url, JSONObject.toJSONString(params));
		if(StringUtils.isNotBlank(responseder)){
			JSONObject jsonObject = JSONObject.parseObject(responseder);
			String ticket = jsonObject.getString("ticket");
			System.out.println("临时二维码TICKET:"+ticket);
			pUrl = WxChatAddress.getQRCode(ticket);
			redisCache.setCacheObject(key,pUrl,WxChatCommon.QR_CODE,TimeUnit.SECONDS);
		}
		}
		return pUrl;
	}
	
	@Override
	public Long redisKeyExpireTime() {
		String key = WxChatCommon.QR_CODE_KEY+":"+SecurityUtils.getUserId();
		long expire = redisCache.getExpire(key);
		return expire;
	}
	
	@Override
	public String sendMessage(WxSendMessageDTO wxSendMessageDTO) {
		String mes = null;
			Map<String,Object> params = new HashMap<>();
			params.put("touser",wxSendMessageDTO.getOpenId());
			params.put("template_id",WxChatCommon.TEMPLATE_ID);
			params.put("topcolor","#FF0000");
		
			Map<String,Map<String,Object>> data = new HashMap<>();
			Map<String,Object> data0 = new HashMap<>();
			data0.put("value",wxSendMessageDTO.getFirst());
			data0.put("color","#173177");
			Map<String,Object> data1 = new HashMap<>();
			data1.put("value",wxSendMessageDTO.getDeviceName());
			data1.put("color","#173177");
			Map<String,Object> data2 = new HashMap<>();
			data2.put("value",wxSendMessageDTO.getWarningParameters());
			data2.put("color","#173177");
			Map<String,Object> data3 = new HashMap<>();
			data3.put("value",wxSendMessageDTO.getReferenceValue());
			data3.put("color","#173177");
			Map<String,Object> data4 = new HashMap<>();
			data4.put("value",wxSendMessageDTO.getEarlyWarningValue());
			data4.put("color","#173177");
			Map<String,Object> data5 = new HashMap<>();
			data5.put("value",wxSendMessageDTO.getWarningTime());
			data5.put("color","#173177");
			Map<String,Object> data6 = new HashMap<>();
			data6.put("value",wxSendMessageDTO.getRemark());
			data6.put("color","#173177");
			data.put("first",data0);
			data.put("thing3",data1);
			data.put("character_string8",data2);
			data.put("thing12",data3);
			data.put("thing10",data4);
			data.put("time2",data5);
			data.put("remark",data6);
			params.put("data",data);
			String url = WxChatAddress.sendMessage(getToken());
			String responseder = HttpUtils.sendPost2(url, JSONObject.toJSONString(params));
			System.out.println("发送信息响应数据："+responseder);
			if(StringUtils.isNotBlank(responseder)){
				JSONObject jsonObject = JSONObject.parseObject(responseder);
				String errmsg = jsonObject.getString("errmsg");
				if("ok".equals(errmsg)){
					mes = errmsg;
				}else {
					String errcode = jsonObject.getString("errcode");
					mes = errcode+":"+errmsg;
				}
			}
			return mes;
		}

	@Override
	public PrepayResponse prepay() {

// 或者获取文件路径
		String path = getClass().getClassLoader().getResource("key/apiclient_key.pem").getPath();
		Config config =
				new RSAAutoCertificateConfig.Builder()
						.merchantId(WxChatCommon.MCH_ID)
						.privateKeyFromPath(path)
						.merchantSerialNumber(WxChatCommon.MERCHANT_SERIAL_NUMBER)
						.apiV3Key(WxChatCommon.API_V3_KEY)
						.build();
		// 构建service
		NativePayService service = new NativePayService.Builder().config(config).build();
		// request.setXxx(val)设置所需参数，具体参数可见Request定义
		PrepayRequest request = new PrepayRequest();
		Amount amount = new Amount();
		amount.setTotal(100);
		request.setAmount(amount);
		request.setAppid("wxa9d9651ae******");
		request.setMchid("190000****");
		request.setDescription("测试商品标题");
		request.setNotifyUrl("https://notify_url");
		request.setOutTradeNo("out_trade_no_001");
		// 调用下单方法，得到应答
		return service.prepay(request);
	}

	/**
	 * 默认告警时间
	 * @return
	 */
	private static  String alarmTime(){
			DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime time = LocalDateTime.now();
			return df.format(time);
		}
		
		
		
		
}
